package repo

import (
	"gitee.com/linxing_3/sr-core/domain/dao/scope"
	"gitee.com/linxing_3/sr-core/domain/logger"
	"gitee.com/linxing_3/sr-core/domain/model"
	"gitee.com/linxing_3/sr-core/domain/repo"
	"gitee.com/linxing_3/sr-core/plugins/storage/cache"
	"gitee.com/linxing_3/sr-core/plugins/storage/database"
	"gitee.com/linxing_3/sr-core/yerr"
	"gitee.com/mkwchecking/sr-admin/apps/admin/entity"
	"github.com/gin-gonic/gin"
)

func NewSysApi(dataset database.IDataSet, cache cache.ICache) *SysApi {
	return &SysApi{
		Wrapper: logger.Default("domain", "admin.repo.SysApi"),
		IRepo:   repo.NewSet[entity.SysApi](dataset, cache),
	}
}

type SysApi struct {
	logger.Wrapper

	repo.IRepo[entity.SysApi]
}

func (s *SysApi) InstallFromGin(g *gin.Engine) error {
	if g == nil {
		return yerr.ErrDataNotfound.Errorf("gin engine is nil")
	}

	ents := make([]*entity.SysApi, 0)
	for idx, v := range g.Routes() {
		a := &entity.SysApi{
			GAIntPK: model.GAIntPK{
				Id: idx,
			},
			Path:    v.Path,
			Method:  v.Method,
			Title:   v.Path,
			Handler: v.Handler,
		}
		a.SetGroup("")
		ents = append(ents, a)
	}

	_, err := s.CreateMulti(ents, scope.WithConflictUpdateAll("id"), scope.WithUnLog())
	return err
}
